/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.liquidByte.trafficMustang.server.business;

import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import org.liquidByte.trafficMustang.server.dataModel.Avaliacao;
import org.liquidByte.trafficMustang.server.dataModel.Trecho;
import org.liquidByte.trafficMustang.server.dataModel.Usuario;
import org.liquidByte.trafficMustang.server.repository.AvaliacaoRepository;
import org.liquidByte.trafficMustang.server.services.AvaliacaoService;
import org.liquidByte.trafficMustang.server.services.BusinessException;
import org.liquidByte.trafficMustang.server.services.MainService;
import org.liquidByte.trafficMustang.server.services.UsuarioService;

/**
 *
 * @author Alexandre
 */
@Stateless
public class AvaliacaoBO implements AvaliacaoService {
    
    private static final int VARIACAO_MAXIMA = 3;

    @EJB
    private AvaliacaoRepository repository;
    @EJB
    private UsuarioService usuarioService;
    @EJB
    private MainService mainService;

    public void registrar(Avaliacao avaliacao) throws BusinessException {
        avaliacao.setAvalPend(false);
        this.repository.persist(avaliacao);
        
        this.usuarioService.qualificar(avaliacao.getUsrIdAvld(), avaliacao.getAvalQlf(), VARIACAO_MAXIMA);
    }

    public List<Avaliacao> getPendente(Usuario usuario) {
        return this.repository.get(usuario, true);
    }

    public void nova(Trecho trecho) {
        Usuario pasg = trecho.getPasgId().getUsuario();
        Usuario mot = trecho.getDeslcId().getMotrId().getUsuario();
        
        Avaliacao avalPasg = new Avaliacao();
        avalPasg.setAvalPend(true);
        avalPasg.setAvalQlf(0);
        avalPasg.setTrecId(trecho);
        avalPasg.setUsrIdAvlr(pasg);
        avalPasg.setUsrIdAvld(mot);
        this.repository.persist(avalPasg);
        
        Avaliacao avalMot = new Avaliacao();
        avalMot.setAvalPend(true);
        avalMot.setAvalQlf(0);
        avalMot.setTrecId(trecho);
        avalMot.setUsrIdAvlr(mot);
        avalMot.setUsrIdAvld(pasg);
        this.repository.persist(avalMot);
        
        this.repository.flush();
        this.mainService.avaliacaoPut(pasg, avalPasg);
        this.mainService.avaliacaoPut(mot, avalMot);
    }
}
